<script setup lang="ts">
import {
  componentPagerApi,
  componentGroupApi,
  componentGroupDelApi,
  componentGroupAddApi,
  componentDelApi,
  componentMoveApi,
} from "@/api/activity";

const emits = defineEmits(["edit","add"]);

const myComponentDialog = ref(false),
  groupDialogTitle = ref(""),
  groupFormData: any = ref({ status: 0 }),
  groupDialogVisiable = ref(false),
  submitLoading = ref(false),
  treeData = ref<Array<any>>([]),
  treeSelectData = ref<Array<any>>([]),
  componentsFilter = ref<any>({
    currentPage: 1,
    showCount: 15,
  }),
  displayComponents = ref<Array<any>>([]),
  myComponentsList = ref<Array<any>>([]),
  selectComponent = ref({}),
  moveGroupForm = ref<any>({}),
  moveGroupDialog = ref(false);

const groupFormRef = ref(),
  LeftTreeRef = ref(),
  moveGroupRef = ref();

// 更多组件
const openMyComponents = () => {
  myComponentDialog.value = true;
  selectComponent.value = {};
};

const handleCommand = (command: string, component: any) => {
  if (command === "apply") {
    let config = JSON.parse(component.comConfig);
    emits('add',{ name: component.name, type: config.type }, config);
    myComponentDialog.value = false;
  } else if (command === "edit") {
    emits("edit", component);
  }
};

// 新增分组
const createTagGroup = (parent?: any) => {
  groupDialogTitle.value = "新建分组";
  if (groupFormRef.value) {
    groupFormRef.value.resetFields();
    groupFormData.value = { status: 0 };
  }
  groupDialogVisiable.value = true;
};

// 编辑分组
const editGroup = async (data: any) => {
  groupDialogTitle.value = `编辑分组【${data.name}】`;
  if (groupFormRef.value) {
    groupFormRef.value.resetFields();
  }
  groupFormData.value = {
    ...data,
  };
  groupDialogVisiable.value = true;
};

// 删除分组
const delGroup = (data: any) => {
  ElMessageBox.confirm(`是否删除【${data.name}】`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let rs = await componentGroupDelApi({ id: data.id });
    if (rs.code === 200) {
      ElMessage.success("删除成功");
      if (data.id == componentsFilter.value.categoryId) {
        componentsFilter.value.categoryId = "";
        getMyComponent(true);
      }
      // LeftTreeRef.value.removeTreeNode(data); // 删除树节点的数据
      getComponentGroup()
    }
  });
};

// 保存分组
const submitGroupForm = () => {
  groupFormRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true;
      let rs = await componentGroupAddApi(groupFormData.value);
      if (rs.code == 200) {
        groupDialogVisiable.value = false;
        ElMessage.success(
          `${groupFormData.value["id"] ? "编辑" : "添加"}分类成功`
        );
        getComponentGroup();
      }
      submitLoading.value = false;
    }
  });
};

// 获取组件分组列表
const getComponentGroup = async () => {
  const rs = await componentGroupApi({ currentPage: 1, showCount: -1 });
  if (rs.code == 200) {
    treeSelectData.value = rs.payload;
    treeData.value = [
      {
        id: "all",
        name: "全部",
        children: [],
      },
    ].concat(rs.payload);
  }
};

// 组件分组筛选
const getTreeNodeId = (data: any) => {
  if (data.id == "all") {
    componentsFilter.value.categoryId = "";
  } else componentsFilter.value.categoryId = data.id;
  getMyComponent(true);
};

// 获取我的组件列表
const getMyComponent = async (refresh = false) => {
  if (refresh) {
    componentsFilter.value.currentPage = 1;
  }
  const rs: any = await componentPagerApi(componentsFilter.value);
  if (rs.code == 200) {
    if (rs.page.currentPage == 1 && !componentsFilter.value.categoryId) {
      displayComponents.value = rs.payload.map((item: any) => {
        return { ...item, comConfig: JSON.parse(JSON.parse(item.comConfig).comConfig) };
      });
    }
    componentsFilter.value.totalResult = rs.page.totalResult;
    myComponentsList.value = rs.payload;
  }
};

const handleCurrentChange = (page: number) => {
  componentsFilter.value.currentPage = page;
  getMyComponent(true);
};

const handelImport = () => {
  emits("edit");
};

// 批量删除
const handleDel = async () => {
  let ids: any = [];
  for (let key in selectComponent.value) {
    if (selectComponent.value[key] === true) ids.push(key);
  }
  if (ids.length == 0) {
    ElMessage({
      message: "请先选择要删除的组件",
      type: "warning",
    });
    selectComponent.value = {};
    return;
  }
  ElMessageBox.confirm(`确认删除吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    submitLoading.value = true;
    const rs = await componentDelApi({ ids });
    if (rs.code == 200) {
      ElMessage({
        showClose: true,
        message: "删除成功",
        type: "success",
      });
      getMyComponent(true);
      selectComponent.value = {};
    }
    submitLoading.value = false;
  });
};

// 批量移动分组
const handleChangeGroup = () => {
  let ids: any = [];
  for (let key in selectComponent.value) {
    if (selectComponent.value[key] === true) ids.push(key);
  }
  if (ids.length == 0) {
    ElMessage({
      message: "请先选择要移动的组件",
      type: "warning",
    });
    selectComponent.value = {};
    return;
  }
  moveGroupForm.value.ids = ids;
  moveGroupDialog.value = true;
};

// 保存批量修改分组
const submitMoveGroup = () => {
  moveGroupRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true;
      const rs = await componentMoveApi(moveGroupForm.value);
      if (rs.code == 200) {
        ElMessage({
          showClose: true,
          message: "保存成功",
          type: "success",
        });
      }
      submitLoading.value = false;
      moveGroupDialog.value = false;
      selectComponent.value = {};
      getMyComponent(true);
    }
  });
};

onMounted(() => {
  getMyComponent();
  getComponentGroup();
});

defineExpose({ refresh: getMyComponent });
</script>
<template>
  <div class="component-group">
    <div class="component-group_title">
      <span>我的组件</span>
      <el-button
        color="#999999"
        link
        @click="componentsFilter.fold = !componentsFilter.fold"
        >{{ componentsFilter.fold ? "展开" : "收起" }}</el-button
      >
    </div>
    <Transition name="expand">
      <div v-show="!componentsFilter.fold" class="component-group_el">
        <template v-for="item in displayComponents">
          <div
            class="component-group_el-item"
            @click="
              emits('add',
                { name: item.name, type: item.comConfig.type },
                item.comConfig
              )
            "
          >
            <img :src="item.icon" alt="" />
            <div>{{ item.name }}</div>
          </div>
        </template>
        <div class="component-group_el-item" @click="openMyComponents">
          <el-button link type="primary">更多组件</el-button>
        </div>
      </div>
    </Transition>
  </div>
  <Dialog
    v-model="myComponentDialog"
    title="我的组件"
    :width="800"
    custom-class="mycomponent-dialog"
  >
    <l-r-content-index>
      <template #title>
        <h3>组件分组</h3>
        <el-button type="primary" @click="createTagGroup">
          <el-icon>
            <Plus />
          </el-icon>
          <span style="margin-left: 10px">新增分组</span>
        </el-button>
      </template>
      <template #side-content>
        <LeftTree
          ref="LeftTreeRef"
          :treeData="treeData"
          :disableSelect="false"
          :currentNodeKey="componentsFilter.categoryId || 'all'"
          showAdd="nodeType"
          @getTreeNodeId="getTreeNodeId"
          @edit="editGroup"
          @del="delGroup"
        ></LeftTree>
      </template>
      <MainContentSearchBarWrapper>
        <div class="activity-component_container">
          <el-row :gutter="20">
            <el-col :span="6" v-for="item in myComponentsList" :key="item.id">
              <div class="activity-component_item">
                <img :src="item.icon" alt="" />
                <div>{{ item.name }}</div>
                <el-dropdown
                  class="more-icon"
                  @command="handleCommand($event, item)"
                >
                  <el-icon><MoreFilled /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="apply">应用</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-checkbox
                  v-model="selectComponent[item.id]"
                  class="select-icon"
                />
              </div>
            </el-col>
          </el-row>
          <el-empty
            v-if="myComponentsList.length == 0"
            description="暂无数据"
          />
        </div>
        <div class="activity-component_pager">
          <el-pagination
            v-model:currentPage="componentsFilter.currentPage"
            v-model:pageSize="componentsFilter.showCount"
            background
            layout="total, prev, pager, next, jumper"
            :total="componentsFilter.totalResult"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
        <div class="activity-component_footer">
          <el-button @click="handelImport">导入</el-button>
          <div>
            <el-button @click="handleDel" :loading="submitLoading"
              >批量删除</el-button
            >
            <el-button @click="handleChangeGroup">批量移动到</el-button>
          </div>
        </div>
      </MainContentSearchBarWrapper>
    </l-r-content-index>
    <template #footer>
      <div></div>
    </template>
  </Dialog>
  <!-- 分组管理 -->
  <Dialog
    v-model="groupDialogVisiable"
    :title="groupDialogTitle"
    :loading="submitLoading"
    :width="500"
    @confirm="submitGroupForm"
  >
    <el-form :model="groupFormData" ref="groupFormRef" label-width="120px">
      <el-form-item
        label="分组名称"
        prop="name"
        :rules="[
          { required: true, message: '请填写分组名称', trigger: 'blur' },
        ]"
      >
        <el-input
          type="text"
          placeholder="请输入分组名称"
          clearable
          maxlength="30"
          :show-word-limit="true"
          v-model="groupFormData.name"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="排序" prop="orderNo">
        <el-input-number
          v-model="groupFormData.orderNo"
          :min="1"
          :step="1"
          step-strictly
        />
      </el-form-item>
    </el-form>
  </Dialog>
  <!-- 组件批量修改组 -->
  <Dialog
    v-model="moveGroupDialog"
    title="组件批量修改"
    :loading="submitLoading"
    :width="500"
    @confirm="submitMoveGroup"
  >
    <el-form :model="moveGroupForm" ref="moveGroupRef" label-width="120px">
      <el-form-item
        label="所属分组"
        prop="categoryId"
        :rules="[
          { required: true, message: '请选择所属分组', trigger: 'change' },
        ]"
      >
        <TreeSelect
          v-model="moveGroupForm.categoryId"
          :treeSelectData="treeSelectData"
          :expand-on-click-node="false"
          :check-strictly="true"
          :treeProps="{ label: 'name' }"
          placeholder="请选择分组"
        ></TreeSelect>
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<style lang="scss" scoped>
.component-group_title {
  padding: 8px 12px;
  background-color: #f7f7fa;
  display: flex;
  justify-content: space-between;
}
.component-group_el {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 10px;
  &-item {
    width: 76px;
    height: 76px;
    border: 1px solid transparent;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    font-size: 14px;
    cursor: pointer;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    img {
      display: block;
      width: 38px;
      height: 57px;
      object-fit: contain;
    }
    &:hover {
      border-color: #fb6638;
    }
  }
}
</style>
<style lang="scss">
.mycomponent-dialog {
  .side-panel {
    height: 500px;
    min-height: auto !important;
  }
  .main-content-search-bar-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    .activity-component_container {
      flex: 1;
      width: 100%;
      .activity-component_item {
        position: relative;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: pointer;
        img {
          display: block;
          width: 38px;
          height: 57px;
          object-fit: contain;
          margin: 0 auto;
        }
        .more-icon {
          position: absolute;
          right: 0;
          top: 0;
        }
        .select-icon {
          position: absolute;
          left: 0;
          top: 0;
        }
      }
      .el-empty {
        width: 100%;
      }
    }
    .activity-component_pager {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }
    .activity-component_footer {
      display: flex;
      justify-content: space-between;
    }
  }
  .el-dialog__footer {
    padding: 0;
    padding-top: 0;
    border-top: none;
  }
}
</style>
